import Table from "@/components/Table";
import { Space, Button, message, Modal, Form, Input, FormInstance, Tag, Card } from "antd";
import '@/assets/styles/buttonStyles.css';
import '@/views/system/user/user.css';
import { DataType, ColumnsType } from "@/types/modelTestLog";
import { useEffect, useState } from "react";
import { getCookie } from "@/utils/cookies";
import React from "react";
import 'react18-json-view/src/style.css'
import { useNavigate } from "react-router-dom";
import baseUrl from '@/config'
import { Image } from 'antd';
import Meta from "antd/es/card/Meta";
import LoadingIndicator from '@/components/loading';

const ModelTestLog: React.FC = () => {
    const [pageLoading, setPageLoading] = useState(true);
    const [data, setData] = useState<DataType[]>([]);
    const [form] = Form.useForm();
    const [selInfo, setSelInfo] = useState('');
    const [listNum, setListNum] = useState(0);


    const navigateTo = useNavigate();
    useEffect(() => {
        // 判断是否有token，检测用户是否已登录，如果未登录，给出提示，并将其跳转到登录页
        if (getCookie('token') == null) {
            message.error("尚未登录，不得访问！", 1);
            navigateTo("/login");
            return;
        }
        fetchData(); // 调用获取数据的函数
    }, []);


    const fetchData = async () => {
        try {
            const response = await fetch(baseUrl + '/back/modelTestLog/getLogList', {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                    'token': `${getCookie('token')}`
                },
            });
            setPageLoading(false);
            if (response.ok) {
                // 请求成功
                const data = await response.json();
                // 处理响应数据
                if (data.msg === '操作成功') {
                    const dataWithKeys = data.data.map((item: { id: { toString: () => any; }; }) => ({ ...item, key: item.id.toString() }));
                    setData(dataWithKeys);
                    setListNum(dataWithKeys.length);
                }
                else {
                    message.warning(data.msg, 1);
                }
            } else {
                // 请求失败
                console.error('Error:', response.status);
            }
        } catch (error) {
            console.error('Error:', error);
        }
    };

    const [paramsContent, setParamsContent] = useState<string[]>([]);;

    const [base64Array, setBase64Array] = useState<string[]>([]);
    const [logResArray, setLogResArray] = useState<string[]>([]);

    const showParamsContent = (text: string) => {
        // 在这里处理点击事件，可以使用 text 参数
        const data = JSON.parse(text);
        setParamsContent(data);
        setIsModalOpenParamsContent(true);
    };

    const showResContent = (text: string) => {
        // 在这里处理点击事件，可以使用 text 参数
        const data = JSON.parse(text);
        const details = data.details;
        let bs64 = []
        for (const bs of details) {
            bs64.push(bs.image_base64)
        }
        setBase64Array(bs64);
        let lgs = []
        const resLogs = data.logs;
        for (const lg of resLogs) {
            const tlg = lg.split(':')
            lgs.push(tlg[tlg.length - 1])
        }
        setLogResArray(lgs)
        setIsModalOpenResContent(true);
    };

    const columns: ColumnsType<DataType> = [
        {
            title: "序号",
            dataIndex: "index",
            key: "index",
            render: (_, _record, index) => <span>{index + 1}</span>,
        },
        {
            title: "模型id",
            dataIndex: "modelId",
            key: "modelId",
            className: 'hiddenColumn'
        },
        {
            title: "模型名称",
            dataIndex: "modelName",
            key: "modelName",
        },
        {
            title: "模型测试备注",
            dataIndex: "modelTestText",
            key: "modelTestText",
        },
        {
            title: "模型测试参数",
            dataIndex: "modelParams",
            key: "modelParams",
            render: (text) => {
                return (
                    <>
                        <Button type="link" onClick={() => showParamsContent(text)}>点击查看</Button>
                    </>
                );
            }
        },
        {
            title: "模型测试结果",
            dataIndex: "modelRes",
            key: "modelRes",
            render: (text) => {
                return <>
                    <Button type="link" onClick={() => showResContent(text)}>点击查看</Button>
                </>
            }
        },
        {
            title: "模型测试者",
            dataIndex: "modelTester",
            key: "modelTester",
        },
        {
            title: "测试时间",
            dataIndex: "createTime",
            key: "createTime",
        },
        {
            title: "最后处理时间",
            dataIndex: "updateTime",
            key: "updateTime",
        },
        {
            title: "id",
            dataIndex: "id",
            key: "id",
            className: 'hiddenColumn'
        }
    ];

    const selInfoDetail = async () => {
        try {
            setPageLoading(true);
            const response = await fetch(baseUrl + '/back/modelTestLog/getLogListLikeTester?tester=' + selInfo, {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                    'token': `${getCookie('token')}`
                }
            });
            setPageLoading(false);
            if (response.ok) {
                // 请求成功
                const data = await response.json();
                // 处理响应数据
                if (data.code === 200) {
                    const dataWithKeys = data.data.map((item: { id: { toString: () => any; }; }) => ({ ...item, key: item.id.toString() }));
                    setData(dataWithKeys);
                    setListNum(dataWithKeys.length);
                    message.success(data.msg, 1);
                }
                else {
                    message.warning(data.msg, 1);
                }
            } else {
                // 请求失败
                console.error('Error:', response.status);
            }
        } catch (error) {
            console.error('Error:', error);
        }
    };

    const SubmitButton = ({ form }: { form: FormInstance }) => {
        const [submittable, setSubmittable] = React.useState(false);

        // Watch all values
        const values = Form.useWatch([], form);

        React.useEffect(() => {
            form.validateFields({ validateOnly: true }).then(
                () => {
                    setSubmittable(true);
                },
                () => {
                    setSubmittable(false);
                },
            );
        }, [values]);

        return (
            <Button type="primary" htmlType="submit" disabled={!submittable} onClick={selInfoDetail}>
                查询
            </Button>
        );
    };

    const handleSelInfoChange = (event: { target: { value: React.SetStateAction<string>; }; }) => {
        setSelInfo(event.target.value);
    };

    const [isModalOpenParamsContent, setIsModalOpenParamsContent] = useState(false);
    const [isModalOpenResContent, setIsModalOpenResContent] = useState(false);

    const handleParamsContent = () => {
        setIsModalOpenParamsContent(false);
    }

    const handleResContent = () => {
        setIsModalOpenResContent(false);
    }



    return (
        <>
            <LoadingIndicator loading={pageLoading} />
            <Form form={form} name="validateOnly" layout="inline" autoComplete="off">
                <Form.Item name="name" label="" rules={[{ required: true, message: "查找字段内容不得为空,如不想查找请点击重置!" }]}>
                    <Input placeholder="(按测试者姓名模糊查询）" value={selInfo} onChange={handleSelInfoChange} />
                </Form.Item>
                <Form.Item>
                    <Space>
                        <SubmitButton form={form} />
                        <Button htmlType="reset">重置</Button>
                    </Space>
                </Form.Item>
                <Tag bordered={true} color="green" className="total-tag">
                    共{listNum}条记录
                </Tag>
                <Button type="link" onClick={fetchData}>查询所有</Button>
            </Form>
            <Modal title="测试参数图片如下（最多8张）：" open={isModalOpenParamsContent} okText="确定"
                cancelText="取消" onOk={handleParamsContent} onCancel={handleParamsContent} width="40%" bodyStyle={{ height: 350 }}>
                {paramsContent.map((code: string | undefined, index) => <Image key={index} src={code} style={{ width: 150, height: 150, marginRight: 5, marginBottom: 5 }} />)}
            </Modal>
            <Modal title="测试结果如下（最多8张）：" open={isModalOpenResContent} okText="确定"
                cancelText="取消" onOk={handleResContent} onCancel={handleResContent} width="50%" bodyStyle={{ height: 700 }}>
                {base64Array.map((base64, index) => (
                    <Card
                        key={index}
                        hoverable
                        style={{ display: 'inline-block', width: 180, height: 350, marginRight: 30, marginBottom: 30, verticalAlign: 'middle' }}
                        cover={<Image src={base64} style={{ width: 180, height: 180 }} />}
                    >
                        <Meta title="" description={logResArray[index]} />
                    </Card>
                ))}
            </Modal>
            <Table<DataType> columns={columns} dataSource={data} />
        </>
    );
};

export default ModelTestLog;

